const serv = require("./server");
const fs = require("fs"); 
const front = require("./engine/front");


class App{
	constructor(conf){
		this.config = conf;
	}
	run(){
		let app = this;
		// JSON.stringify(req.headers)
		serv.run(this.config.server, function(req, res){
			res.setHeader("Server", "K-NodeJs-Framework");
			let raw_data = [];
			let total_length = 0;
			req.on("data", function(chunk){
				raw_data.push(chunk);
				total_length += chunk.length;
			});
			
			// let new_raw_data = [];
			let post = {}
			let files = {};
			req.on("end", function(){
				let buf_data = Buffer.concat(raw_data, total_length);
				let data_pos = [];
				for (let i = 0; i < buf_data.length; i++) {
					if (buf_data[i].toString() == 13 && buf_data[i+1].toString() == 10) {
						data_pos.push(i);
					}
				}
				for (let p_i = 0; p_i < data_pos.length; p_i++) {
					if (data_pos[p_i+1]) {
						let block = buf_data.slice(data_pos[p_i], data_pos[p_i + 1]).toString();
						// console.log(p_i, block);
							block = block.replace("\r\n", "");
							block = block.split(";");
							
						let name;
						switch (block.length) {
							case 2:
								name = block[1].split("=")[1];
								name = name.replace(/\"/g,"");
								let value = buf_data.slice(data_pos[p_i + 2], data_pos[p_i + 3]).toString();
								post[name] = value.replace("\r\n", "");
								p_i+=2;
								break;
							case 3:
								name = block[1].split("=")[1];
								name = name.replace(/\W/g, "");
								let filename = block[2].replace("filename=", "");
								filename = filename.replace(/\"/g, "").trim();
								let filetype = buf_data.slice(data_pos[p_i + 1], data_pos[p_i + 2]).toString();
								filetype = filetype.split(":")[1].trim();
								let filetemp = buf_data.slice(data_pos[p_i + 3], data_pos[p_i + 5]);
									filetemp = filetemp.slice(2, filetemp.length);
								fs.writeFileSync("./" + filename, filetemp);
								if (!files[name]) {
									files[name] = [];
								}
								
								let fileinfo = {
									name: filename,
									type: filetype,
									temp: filetemp,
									size: filetemp.length,
									errno: 0,
									error: ""
								}
								files[name].push(fileinfo);
								p_i += 4;
								break;
						}
					} 
				}
				console.log(post);
				console.log(files);
				front.dispatch(req, res, app.config);
			});
		});
	}
} 
exports.run = function (conf) {
	let app = new App(conf);
		app.run();
}